package com.kinon.markett2.view;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.markett2.Constants;
import com.kinon.markett2.MyApplication;
import com.kinon.markett2.R;
import com.kinon.markett2.bluetoothprint.BluetoothPrintFormatUtil;
import com.kinon.markett2.bluetoothprint.BluetoothService;
import com.kinon.markett2.bluetoothprint.DeviceListActivity;
import com.kinon.markett2.bluetoothprint.PicFromPrintUtils;
import com.kinon.markett2.entity.GoodsInfoBean;
import com.kinon.markett2.entity.ItemBean;
import com.kinon.markett2.entity.KVP;
import com.kinon.markett2.entity.PhoneUserBean;
import com.kinon.markett2.sqlbean.BuyGoodsBean;
import com.kinon.markett2.sqlbean.UserBuyBean;
import com.kinon.markett2.tools.CustomDialog;
import com.kinon.markett2.tools.HttpTools;
import com.kinon.markett2.tools.MyShowDialog;
import com.kinon.markett2.tools.NetWorkUtil;
import com.kinon.markett2.tools.SendShopList;
import com.kinon.markett2.tools.SysTimeManage;
import com.kinon.markett2.tools.ToastUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import sunmi.ds.DSKernel;

public class JiesuanjineActivity extends Activity {

    /**
     * 打印信息的集合
     */
//	private ArrayList<DingdanEntity> dayingslist;
//	DayingAdapter dayingAdapter;

    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    // Key names received from the BluetoothService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    // Member object for the services
    public static BluetoothService mService = null;
    String id;
    String token;
    HttpTools httptools = null;
    BluetoothPrintFormatUtil printFormatUtil = null;
    LinkedHashMap<String, LinkedList<String>> menuMsgMap;
    LinkedList<String> gonds;
    ArrayList<GoodsInfoBean> detaillist;
    String jine;
    // T1 客显
    DSKernel mDSKernel;// SDK核心类
    List<ItemBean> items;
    List<KVP> sm;
    String totalamount;
    ArrayList<BuyGoodsBean> buyList;
    private TextView tv_jine;
    private TextView tv_fanhui;
    private EditText et_pay;
    // 手机号支付
    private Button btn_checkPhone;

    // Name of the connected device
    private String mConnectedDeviceName = null;
    // The Handler that gets information back from the BluetoothService
    private final Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED:
                            break;
                        case BluetoothService.STATE_CONNECTING:
                            break;
                        case BluetoothService.STATE_LISTEN:
                        case BluetoothService.STATE_NONE:
//                	print_connect_btn.setText("无连接");
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    break;
                case MESSAGE_READ:
                    break;
                case MESSAGE_DEVICE_NAME:
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    Toast.makeText(JiesuanjineActivity.this, "连接至"
                            + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(JiesuanjineActivity.this, msg.getData().getString(TOAST),
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    /**
     * EditText的监听
     */
    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public synchronized void afterTextChanged(Editable s) {
            if (et_pay.getText().length() == Constants.CARD_LENGTH) {
                String card = et_pay.getText().toString().trim();
                if (!Constants.URGENT_TYPE) {
                    Dingdan(card);
                } else {
                    addSqlite(card);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jiesuanjine);
        initRes();
        Log.e("data-card_length", "card_length: " + Constants.CARD_LENGTH);
    }

    ToastUtil toastUtil = new ToastUtil();
    private CustomDialog dialog;
    private String mUserCard = null;

    private void initRes() {
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");
        tv_jine = (TextView) findViewById(R.id.tv_jine);
        et_pay = (EditText) findViewById(R.id.et_pay);
        btn_checkPhone = (Button) findViewById(R.id.btn_checkPhone);
        btn_checkPhone.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Constants.URGENT_TYPE) {
                    toastUtil.Short(getApplication(), "网络不稳定不能使用手机号支付," +
                            "请刷卡或重新生成订单").setToastBackground(Color.WHITE, 0).show();
                    return;
                }
                dialog = new CustomDialog(2, JiesuanjineActivity.this, new CustomDialog.DialogClickListener() {
                    @Override
                    public void onDialogClick(int btn) {
                        if (btn == 1) {
                            if (TextUtils.isEmpty(mUserCard)) {
                                httptools.phoneCheck(token, dialog.getPhone(), new JsonPhoneCheck());
                            } else {
                                Dingdan(mUserCard);
                            }
                        }
                    }
                });
                dialog.show();
            }
        });
        jine = getIntent().getStringExtra("total");
        tv_jine.setText("￥" + jine);
        et_pay.requestFocus();
        et_pay.addTextChangedListener(watcher);
        tv_fanhui = (TextView) findViewById(R.id.tv_fanhui);
        tv_fanhui.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

//        mDSKernel = DSKernel.newInstance();

        totalamount = getIntent().getStringExtra("totalamount");
        buyList = (ArrayList<BuyGoodsBean>)
                getIntent().getSerializableExtra("buyList");
        if (!Constants.URGENT_TYPE) {
            Show();
        } else {
            addUrgentShow();
            btn_checkPhone.setVisibility(View.GONE);
        }


        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(JiesuanjineActivity.this, "您的设备不支持蓝牙", Toast.LENGTH_SHORT).show();
//			finish();
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            //打开蓝牙
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        if (mService == null) {
            mService = new BluetoothService(JiesuanjineActivity.this, mHandler);
        }
        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(JiesuanjineActivity.this, "蓝牙没有连接", Toast.LENGTH_SHORT).show();
//			return;
            Intent serverIntent = new Intent(JiesuanjineActivity.this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return;
        }
    }

    private class JsonPhoneCheck extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
                super.onSuccess(statusCode, headers, response);
                Gson gson = new Gson();
                PhoneUserBean user = gson.fromJson(response.getString("data"), PhoneUserBean.class);
                mUserCard = user.getNo();
                dialog.setmStrMsg("姓名：" + user.getName() + "\n手机："
                        + user.getUsername() + "\n卡号：" + mUserCard);
                dialog.setmType(1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
            Log.e("lh", errorResponse.toString());
            dialog.setmStrMsg(errorResponse + "");
            dialog.setmType(1);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    /**
     * 打印
     *
     * @param message
     */
    private void sendMessage(String message) {
        if (message.length() > 0) {
            byte[] send;
            try {
                send = message.getBytes("GB2312");
            } catch (UnsupportedEncodingException e) {
                send = message.getBytes();
            }

            mService.write(send);
        }
    }

    private void sendMessage(Bitmap bitmap) {
        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(JiesuanjineActivity.this, "蓝牙没有连接", Toast.LENGTH_SHORT).show();
            return;
        }
        // 发送打印图片前导指令
        byte[] start = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B,
                0x40, 0x1B, 0x33, 0x00};
        mService.write(start);

        /**获取打印图片的数据**/
//		byte[] send = getReadBitMapBytes(bitmap);

        mService.printCenter();
        byte[] draw2PxPoint = PicFromPrintUtils.draw2PxPoint(bitmap);

        mService.write(draw2PxPoint);
        // 发送结束指令
        byte[] end = {0x1d, 0x4c, 0x1f, 0x00};
        mService.write(end);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                if (resultCode == Activity.RESULT_OK) {
                    String address = data.getExtras()
                            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                    mService.connect(device);
                }
                break;
            case REQUEST_ENABLE_BT:
                if (resultCode == Activity.RESULT_OK) {
//                setupChat();
                    Toast.makeText(JiesuanjineActivity.this, "蓝牙已打开", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(JiesuanjineActivity.this, "蓝牙没有打开", Toast.LENGTH_SHORT).show();
//                finish();
                }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.scan:
                // Launch the DeviceListActivity to see devices and do scan
                Intent serverIntent = new Intent(JiesuanjineActivity.this, DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
                return true;
            case R.id.disconnect:
                // disconnect
                mService.stop();
                return true;
        }
        return false;
    }

    /**
     * 打印格式以及打印内容
     */
    private void print(String totalamount, String total, String orderno, String order_time,
                       String name, String phone) {
        sendMessage(printFormatUtil.printTitle("                 智慧食堂") + "\n");
        sendMessage(printFormatUtil.printTitle("************************************************") + "\n");
        sendMessage("名称" + "               " + "数量" + "                 " + "价格" + " \n");
        menuMsgMap.put("", gonds);
        sendMessage(printFormatUtil.printMenuMSG(menuMsgMap));
        sendMessage("数量：" + totalamount + "份" + "   ");
        sendMessage("总价：" + total + "元" + " \n");
        sendMessage("订单编号：" + orderno + " \n");
        sendMessage("下单时间：" + order_time + " \n");
        if (!Constants.URGENT_TYPE) {
            sendMessage("姓名：" + name + " \n");
            sendMessage("联系电话：" + phone + " \n");
        } else {
            sendMessage("卡号：" + name + " \n");
        }

        sendMessage(printFormatUtil.printTitle("***********************************************") + "\n");
        sendMessage(printFormatUtil.printTitle("             请妥善保管好购物凭证" + "\n"));
        sendMessage(printFormatUtil.printTitle("                 谢谢惠顾！") + "\n");
        sendMessage(" \n");
        sendMessage(" \n");
        sendMessage(" \n");
        sendMessage(" \n");
    }

    /**
     * T1mini打印
     */
    private void miniPrint(String totalamount, String total, String orderno, String order_time,
                           String name, String phone) {
        sendMessage(printFormatUtil.printTitle("    智慧食堂") + "\n");
        sendMessage(printFormatUtil.printTitle("********************************") + "\n");
        sendMessage("名称" + "         " + "数量" + "           " + "价格" + " \n");
        menuMsgMap.put("", gonds);
        sendMessage(printFormatUtil.printMenuMSG(menuMsgMap));
        sendMessage("数量：" + totalamount + "份" + "   ");
        sendMessage("总价：" + total + "元" + " \n");
        sendMessage("订单编号：" + orderno + " \n");
        sendMessage("下单时间：" + order_time + " \n");
        if (!Constants.URGENT_TYPE) {
            sendMessage("姓名：" + name + " \n");
            sendMessage("联系电话：" + phone + " \n");
        } else {
            sendMessage("卡号：" + name + " \n");
        }

        sendMessage(printFormatUtil.printTitle("********************************") + "\n");
        sendMessage(printFormatUtil.printTitle("       请妥善保管好购物凭证" + "\n"));
        sendMessage(printFormatUtil.printTitle("          谢谢惠顾！") + "\n");
        sendMessage(" \n");
        sendMessage(" \n");
        sendMessage(" \n");
        sendMessage(" \n");
    }

    /**
     * 订单支付
     */
    private void Dingdan(String card) {
        synchronized (card) {
            et_pay.setText("");

            if (NetWorkUtil.isNetwork(getApplicationContext()) == false) {
                Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                return;
            }
            id = getIntent().getStringExtra("orderid");
            if (httptools == null) {
                httptools = new HttpTools(JiesuanjineActivity.this);
            }

            httptools.shouyinconfirm(token, id, card, new JsonDingdan());
        }
    }

    /**
     * 请求打印的订单详情
     */
    private void Daying(String id) {
        detaillist = new ArrayList<GoodsInfoBean>();
        menuMsgMap = new LinkedHashMap<String, LinkedList<String>>();
        gonds = new LinkedList<String>();
//		shuliang="";
        if (httptools == null) {
            httptools = new HttpTools(JiesuanjineActivity.this);
        }
        httptools.getOrderdetial(token, id,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            if (code == true) {
                                JSONObject object = response.getJSONObject("data");
                                String username = object.getString("user");
                                String phone = object.getString("phone");
                                String totalamount = object.getString("count");
                                String total = object.getString("num");
                                JSONObject data = object.getJSONObject("wsbill");
                                String orderno = data.getString("ref");
                                String order_time = data.getString("biz_dt");
                                JSONArray array = object.getJSONArray("goods");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject goods = array.getJSONObject(i);
                                    String name = goods.getString("name");
                                    String amount = goods.getString("goods_count");
                                    String price = goods.getString("inventory_money");
                                    detaillist.add(new GoodsInfoBean(name, amount, price, "", ""));
                                    gonds.add(" \n" + name);
                                    gonds.add("*" + amount);
                                    gonds.add("" + price);
                                }
                                if (MyApplication.subModel.equals("T1mini")) {
                                    miniPrint(totalamount, total, orderno, order_time, username, phone);
                                } else {
                                    print(totalamount, total, orderno, order_time, username, phone);
                                }
                            } else {
                                Toast.makeText(JiesuanjineActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                                          String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                        Toast.makeText(JiesuanjineActivity.this, "网络请求超时",
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 副屏显示商品列表
     */
    private void Show() {
        items = new ArrayList<>();
        sm = new ArrayList<>();
        String orderid = getIntent().getStringExtra("orderid");
        if (httptools == null) {
            httptools = new HttpTools(JiesuanjineActivity.this);
        }
        httptools.getOrderdetial(token, orderid,
                new JsonHttpResponseHandler() {
                    //					@Override
//					public void onStart() {
//						MyShowDialog.showLoadingDialog(JiesuanjineActivity.this, "请稍候....");
//						super.onStart();
//					}
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            Log.i("info", "副屏显示----" + response.toString());
                            if (code == true) {
                                JSONObject object = response.getJSONObject("data");
                                String count = object.getString("count");

                                JSONObject data = object.getJSONObject("wsbill");
                                String num = data.getString("inventory_money");
                                sm.add(new KVP("商品数量", count));
                                sm.add(new KVP("共计", num));
                                JSONArray array = object.getJSONArray("goods");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject goods = array.getJSONObject(i);
                                    String bianhao = goods.getString("code");
                                    String name = goods.getString("name");
                                    String amount = goods.getString("goods_count");
                                    String price = goods.getString("inventory_price");
                                    String total = goods.getString("inventory_money");
                                    items.add(new ItemBean(bianhao, name, price, amount, total));
//									detaillist.add(new GoodsInfoBean(name, amount, price, "",""));
                                }
                                //给副屏发送商品列表数据
//                                showBuyInfo();
//								tv_jine.setText("￥"+num);
//								print();
                            } else {
                                Toast.makeText(JiesuanjineActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }

    /**
     * 发送信息到副屏
     */
    private void showBuyInfo() {
        SendShopList sendShopList = new SendShopList(getApplicationContext(), mDSKernel, items, sm);
        sendShopList.getInstance(getApplicationContext(), mDSKernel, items, sm);
        sendShopList.send(false, "");
    }

    private void addSqlite(String card) {
        synchronized (card) {
            et_pay.setText("");

            menuMsgMap = new LinkedHashMap<String, LinkedList<String>>();
            long sysTime = System.currentTimeMillis();
            String id = SysTimeManage.getInstage().getOrderId(sysTime);
            String date = SysTimeManage.getInstage().getDate(sysTime);
            String time = SysTimeManage.getInstage().getDateTime(sysTime);

            Log.e("lh", "buyList.size==" + buyList.size());
            if (buyList.size() == 0) {
                Toast.makeText(getApplicationContext(), "数据异常",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            UserBuyBean userBuy = new UserBuyBean(id, card, time, date, Double.parseDouble(jine), 0, buyList);

            boolean save = userBuy.save();
            for (BuyGoodsBean i : buyList) {
                i.save();
            }

//
            if (save) {
                if (MyApplication.subModel.equals("T1mini")) {
                    miniPrint(totalamount, jine, id, time, card, null);
                } else {
                    print(totalamount, jine, id, time, card, null);
                }
                Toast.makeText(getApplicationContext(), "刷卡成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(JiesuanjineActivity.this, PayresultActivity.class);
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(getApplicationContext(), "刷卡失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void addUrgentShow() {
        gonds = new LinkedList<>();
        items = new ArrayList<>();
        sm = new ArrayList<>();
        sm.add(new KVP("商品数量", totalamount));
        sm.add(new KVP("共计", jine));
        for (BuyGoodsBean i : buyList) {

            gonds.add(" \n" + i.getName());
            gonds.add("*" + i.getAmount() + "");
            gonds.add("" + i.getPrice() + "");

            items.add(new ItemBean(i.getCode(), i.getName(), i.getPrice() + "",
                    i.getAmount() + "", i.getPrice() * i.getAmount() + ""));
        }
//        showBuyInfo();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    public class JsonDingdan extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(JiesuanjineActivity.this, "订单支付中....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
//			Log.i("info", "jiesuan---"+response.toString());
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    Daying(id);
                    Toast.makeText(JiesuanjineActivity.this, msg, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(JiesuanjineActivity.this, PayresultActivity.class);
                    intent.putExtra("jine", jine);
                    startActivity(intent);
                    finish();
                } else {
                    et_pay.setText("");
                    Toast.makeText(JiesuanjineActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            MyShowDialog.closeLoadingDialog();
            Log.e("lh", "responseString== " + responseString);
            Toast.makeText(JiesuanjineActivity.this, "网络请求超时",
                    Toast.LENGTH_SHORT).show();
        }

    }
}
